package com.jyniubi.core.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jyniubi.core.mapper.DictMapper;
import com.jyniubi.core.pojo.dto.ExcelDataDTO;
import com.jyniubi.core.pojo.entity.Dict;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据字段 excel 监听器
 */

@Slf4j
@NoArgsConstructor
public class DictExcelDataListener extends AnalysisEventListener<ExcelDataDTO> {
    private DictMapper dictMapper;
    private static final int BATCH_COUNT = 5;
    List<ExcelDataDTO> list = new ArrayList<>();

    public DictExcelDataListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDataDTO dictData, AnalysisContext analysisContext) {
        log.info("解析到一条数据：{}", dictData);
        Long id = dictData.getId();
        Integer count = dictMapper.selectCount(Wrappers.lambdaQuery(Dict.class)
                .eq(Dict::getId, id));
        if (count > 0) {
            return;
        }
        Dict dict = new Dict();
        dict.setId(dictData.getId());
        dict.setParentId(dictData.getParentId());
        dict.setValue(dictData.getValue());
        dict.setName(dictData.getName());
        dict.setDictCode(dictData.getDictCode());
        dictMapper.insert(dict);

        //todo:将字典数据导入数据库表中优化为批量导入，现在的问题是报错
//        list.add(dictData);
//        if (list.size()>=BATCH_COUNT){
//            saveData();
//            list.clear();
//        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("数据字典全部存储数据库");
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库",list.size());
//        dictMapper.insertBatch(list);
        log.info("存储数据库成功");
    }

}
